<template>
  <div class="app-container">
    <div class="attendance-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="输入搜索：" prop="name" class="el-form-item">
          <el-input v-model="queryParams.name" placeholder="姓名" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="状态：" prop="status" class="el-form-item">
          <el-select v-model="queryParams.attendance" placeholder="请选择状态" clearable style="width: 240px">
            <el-option v-for="dict in attendance_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="打卡日期：" class="el-form-item">
          <el-date-picker v-model="queryParams.attendanceDate" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item class="el-form-item">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table ref="multipleTable" v-loading="loading" :data="list" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="姓名" align="center" prop="userName" :show-overflow-tooltip="true" />
        <el-table-column label="岗位" align="center" prop="positionName" :show-overflow-tooltip="true" />
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="{ row }">
            <el-tag size="mini" v-if="row.attendance === '-1'" type="success">
              正常
            </el-tag>
            <el-tag v-else size="mini" :type="getTagType(row.attendance)">
              {{ attendance_status[row.attendance].label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上班打卡" align="center" prop="loginTime" width="180">
          <template slot-scope="{ row }">
            <span>{{ row.attendanceUpTime ? parseTime(row.attendanceUpTime) : '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="下班打卡" align="center" prop="loginTime" width="180">
          <template slot-scope="{ row }">
            <span>{{ row.attendanceDownTime ? parseTime(row.attendanceDownTime) : '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="补卡情况" align="center" prop="browser" :show-overflow-tooltip="true">
          <template slot-scope="{ row }">
            <span>{{ row.isRepair === '1' ? '已补卡' : '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="补卡时间" align="center" prop="loginTime" width="180">
          <template slot-scope="{ row }">
            <span>{{ row.isRepair === '1' ? parseTime(row.replacementDate) : '--' }}</span>
          </template>
        </el-table-column>
          <el-table-column label="创建时间" align="center" prop="loginTime" width="180">
          <template slot-scope="{ row }">
            <span>{{ parseTime(row.createTime)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="{ row }">
            <el-button size="mini" type="text" @click="handleJump(row)">考勤情况</el-button>
            <el-button v-show="row.attendance === '2' || row.attendance === '4'" size="mini" type="text"
              @click="handleRecord(row)">补卡</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
      <div class="checked-container">
        <el-checkbox v-model="checked" @change=changeChecked()>全选</el-checkbox>
        <el-popover placement="top" width="160" v-model="visible">
          <p>是否批量补卡？</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="visible = false">取消</el-button>
            <el-button type="primary" size="mini" @click="handleSure">确定</el-button>
          </div>
          <el-button slot="reference" size="mini" class="btn-checked">批量补卡</el-button>
        </el-popover>
      </div>
    </div>
  </div>
</template>

<script>
import { list, record } from "@/api/personnel/attendance";
import moment from "moment";

export default {
  name: "Logininfor",
  data() {
    return {
      visible: false,
      checked: false,
      //考勤状态
      attendance_status: [
        { value: '0', label: '正常' },
        { value: '1', label: '迟到' },
        { value: '2', label: '旷工' },
        { value: '3', label: '请假' },
        { value: '4', label: '异常' },
        { value: '5', label: '休息' }
      ],
      // 遮罩层
      loading: true,
      // 选择用户名
      selectName: "",
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 存储选中的行
      selectedRows: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        attendanceDate: undefined,
        userName: undefined,
        status: undefined
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询登录日志列表 */
    getList() {
      this.loading = true;
      if (this.queryParams && this.queryParams.attendanceDate) {
        this.queryParams.attendanceDate = this.moment(this.queryParams.attendanceDate).format("YYYY-MM-DD");
      }
      list(this.queryParams).then(res => {
        this.list = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.pageNum = 1;
      this.queryParams.attendanceDate = '';
    },
    getTagType(value) {
      switch (value) {
        case '0':
          return 'success';
        case '1':
          return 'warning';
        case '2':
          return 'danger';
        case '3':
          return 'warning';
        case '4':
          return 'danger';
        case '5':
          return 'info';
        default:
          return '';
      }
    },
    //补卡
    handleRecord(row) {
      const params = {
        userId: row.userId,
        date: moment().format("YYYY-MM-DD"),
        type: 3
      }
      record(params).then(response => {
        this.$modal.msgSuccess("补卡成功");
        this.getList();
      });
    },
    //全选
    changeChecked() {
      if (this.checked) {
        this.$refs.multipleTable.toggleAllSelection(); // 全选
      } else {
        this.$refs.multipleTable.clearSelection(); // 取消选择
      }
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      if (selection.length === this.list.length) {
        this.checked = true;
      } else {
        this.checked = false;
      }
    },
    //批量补卡
    handleSure() {
      if (this.selectedRows.length === 0) {
        this.$modal.msgError("请选择要补卡的记录");
        this.visible = false;
        return
      }
      const promises = this.selectedRows.map(row => {
        const params = {
          userId: row.userId,
          date: moment().format("YYYY-MM-DD"),
        };
        return record(params)
          .then(response => {
            return response;
          })
          .catch(error => {
            console.error("补卡失败:", error);
            return null;
          });
      });

      Promise.all(promises)
        .then(responses => {
          this.$modal.msgSuccess("所有补卡请求已处理");
          this.getList();
        })
        .catch(error => {
          console.error("处理补卡请求时出错:", error);
        });
    },
    //考勤情况
    handleJump(row) {
      this.$router.push({ path: `/personnel/attendance/detail?userId=${row.userId}&userName=${row.userName}` });
    }
  }
};
</script>
<style lang="scss" scoped>
.attendance-container {
  .el-form-item {
    margin-left: 20px;
  }

  .checked-container {
    position: relative;
    top: -30px;
    left: 20px;

    .btn-checked {
      margin-left: 10px;
    }
  }
}
</style>
